import screen from '../../../../data/enum';
Component({
  lifetimes: {
    attached: function () {
      this.setPaddingTop();
      const child = this.selectComponent('#refresher');
      if (child) {
        child.allHideView();
      }
      this.getCityHistory(); //获取搜索城市历史
      this.getAllCityList(); //获取所有城市
      this.industryType();
      // 初始化城市信息
      this.citySearch('', "hostCity");
      // 初始化获取数据
      this.getHomeData({
        key: "up"
      });
    },
    detached: function () {},
  },
  data: {
    showProjectTypes: false,
    // 筛选表单字段
    searchForm: {
      "current": 1, //第几页 从1开始
      "size": 10, //每页展示长度  
      "sortType": 0, //	0=综合 1=最新发布 2=要价从高到低 3=要价从低到高 必填 
      "projectShortName": "", //	搜索框的值 名称 
      "projectIndustrys": [], //行业 多选 values [0, 1, 2] 数组 
      "projectTypes": [], //类型 多选 [0, 1, 2] 
      "projectProvinceCode": "", //省份code 
      "projectCityCode": "", //城市code  
      "projectAreaCode": "", //区/县code 
      "establishmentTimeType": null, //	成立时间 0=5-10年 1=10年以上 
      "employeesNumberType": null, //员工人数 0=50人以下 1=50-99人 2=100-999人 3=1000人以上 
      "operatingIncomeType": null, //营业收入 0=200w以下 1=200-499万 2=500-3000w 3=3000-5000w 4=5000-1亿 5=1亿以上 
      "operatingIncomeValue": null, //营业收入 手动填写 
      "profitType": null, //利润 0=200w一下 1=200-499w 2=500-3000w 3=3000-5000w 4=5000-1亿 5=1亿以上 
      "profitMin": null, //	利润 最小值 
      "profitMax": null //利润 最大值 
    },
    top: 0,
    showCity: false,
    showScreen: false, //显示、隐藏筛选、
    // 筛选
    screenLeftSelect: screen.screen[0].id,
    screenLeft: screen.screen,
    // 行业
    option2: screen.typeAndProfession,
    allCityList: [], //获取所有城市列表
    cityCurrentIndex: 0,
    isSelectCity: "", //选中的城市
    isSelectProvince: "", //选中的省
    isSelectDistrict: "", //选中的地区
    isSelectCityLabel: "", //选中的城市
    isSelectProvinceLabel: "", //选中的省
    isSelectDistrictLabel: "", //选中的地区
    hostCity: [], //热门城市 
    cityHistory: [], // 搜索城市历史
    myCity: [], //定位城市
    myDistrict: [], //选中城市后返回的地区信息   
    myProvinceCity: [], //选中城市后返回的地区信息   
    list: [],
    option1: [{
      text: '深圳',
      value: 0
    }, {
      text: '行业',
      value: 1
    }, ],
    option3: [{
      text: '筛选',
      value: 0
    }, {
      text: '好评排序',
      value: 1
    }, {
      text: '销量排序',
      value: 2
    }, ],
    synthesisValue: 0,
    synthesis: [{
      text: '综合',
      value: 0
    }, {
      text: '最新发布',
      value: 1
    }, {
      text: '要价从高到低',
      value: 2
    }, {
      text: '要价从低到高',
      value: 3
    }],
    value1: 0,
    value2: 0,
    value3: 0,
    value4: 0,
    isScroll: false,
    activateClass: false
  },
  methods: {
    // 获取行业类型
    async industryType() {
      var screenList = [{
        "label": "类型",
        "id": "projectTypes",
        "rows": [{}]
      }, {
        "label": "行业",
        "id": "projectIndustrys",
        "rows": [{}]
      }];
      let res = await getApp().http.dictTypeList({});
      if (res.errorCode === 200) {
        let projectIndustry = res.data.project_industry;
        let projectType = res.data.project_type;
        for (let i in res.data) {
          // 行业
          if (i === "project_industry") {
            screenList[1].rows = projectIndustry.map(item => {
              return {
                "value": item.value,
                "label": item.label,
                "index": item.value,
                "pid": "projectIndustrys"
              }
            });
          }
          // 类型
          if (i === "project_type") {
            screenList[0].rows = projectType.map(item => {
              return {
                "value": item.value,
                "label": item.label,
                "index": item.value,
                "pid": "projectTypes"
              }
            });
          }
          this.setData({
            option2: screenList
          })
        }
      }
    },
    // 清除选中
    ClearSelectKeyValue(e) {
      let {
        key
      } = getApp().utils.getParameter(e);
      if (key === "searchForm.operatingIncomeValue") {
        this.setData({
          'searchForm.operatingIncomeType': null,
        })
      }
      if (key === "searchForm.profitMax" || key === "searchForm.profitMin") {
        this.setData({
          "searchForm.profitType": null
        })
      }
    },
    setKeyValue(e) {
      let {
        key
      } = getApp().utils.getParameter(e);
      let {
        value
      } = e.detail;
      console.log(e);
      this.setData({
        [key]: value
      })
    },
    goCitySearch() {
      wx.navigateTo({
        url: '/pages/citySearch/citySearch',
      })
    },
    setAllCity(e) {
      var {
        item,
        key,
        index
      } = getApp().utils.getParameter(e);
      let eumes = [{
        label: "省份",
        code: "provinceCode",
        value: "provinceName",
        name: "isSelectProvinceLabel",
        key: "isSelectProvince",
      }, {
        label: "城市",
        code: "cityCode",
        value: "cityName",
        name: "isSelectCityLabel",
        key: "isSelectCity"
      }, {
        label: "地区",
        code: "areaCode",
        value: "areaName",
        name: "isSelectDistrictLabel",
        key: "isSelectDistrict"
      }];
      let newCityCurrentIndex = index + 1 > 2 ? 2 : index + 1;
      console.log({
        item,
        key,
        index,
        newCityCurrentIndex,
        cityCurrentIndex: this.data.cityCurrentIndex,
      })
      let formData = {
        "cityName": "",
        "cityCode": "",
      }
      if (key === "isSelectProvince") {
        formData["provinceCode"] = item.provinceCode;
        this.citySearch(formData, 'myProvinceCity');
        this.setData({
          isSelectCityLabel: "",
          isSelectCity: "",
          isSelectDistrictLabel: "",
          isSelectDistrict: "",
        })
      }
      if (key === "isSelectCity") {
        formData["provinceCode"] = '';
        formData["cityCode"] = item.cityCode;
        this.citySearch(formData, 'myDistrict');
        this.setData({
          isSelectDistrict: "",
          isSelectDistrictLabel: "",
        })
      }
      this.setData({
        [key]: item[eumes[index].code],
        [eumes[index].name]: item[eumes[index].value],
        cityCurrentIndex: Number(newCityCurrentIndex),
      })
    },
    getAllCityList() {
      let formData = {
        cityName: "province",
        cityCode: ""
      };
      this.citySearch(formData, "allCityList");
    },
    // 获取城市搜索历史
    getCityHistory() {
      var that = this;
      wx.getStorage({
        key: "selectCityItem",
        success(res) {
          that.setData({
            cityHistory: [res.data],
          });
          setTimeout(() => {
            that.screenCity({
              currentTarget: {
                dataset: {
                  item: res.data,
                  key: 'isSelectCity',
                  index: 0
                }
              }
            });
          }, 1000)
        }
      })
    },
    // 确认筛选
    confirmScreenSelect() {
      this.setData({
        ['searchForm.current']: 1,
      })
      this.setData({
        showScreen: false,
      });
      let {
        establishmentTimeType,
        employeesNumberType,
        operatingIncomeType,
        operatingIncomeValue,
        profitType,
      } = this.data.searchForm;
      if (establishmentTimeType != null || employeesNumberType != null || operatingIncomeType != null || operatingIncomeValue != null || profitType != null) {
        this.setData({
          activateClass: true
        })
      }
      this.getHomeData({
        key: "up",
      });
      const child = this.selectComponent('#dropdownScreen');
      child.toggle(false)
    },
    // 获取城市信息
    citySearch(data, key) {
      let formData = {
        cityName: "hotCitys",
        cityCode: ""
      };
      if (data) {
        formData = data;
      }
      // 获取热门城市
      getApp().http.citySearch(formData).then(res => {
        if (res.errorCode === 200) {
          if (formData.cityName === "hotCitys") {
            this.citySearch({
              cityCode: res.data[0].cityCode,
              cityName: "",
            }, 'myDistrict')
          }
          this.setData({
            [key]: res.data || [],
            // isSelectCity: res.data[0]?.cityCode
          })
        }
      });
      // 获取当前城市信息 
    },
    // 筛选-确定选择
    confirmCitySelect() {
      this.setData({
        "searchForm.projectAreaCode": this.data.isSelectDistrict,
        "searchForm.projectCityCode": this.data.isSelectCity,
        "searchForm.projectProvinceCode": this.data.isSelectprovince,
        ['searchForm.current']: 1,
        showCity: false,
      });
      const child = this.selectComponent('#dropdownCity');
      child.toggle(false)
      this.getHomeData({
        key: "up"
      })
    },
    // 筛选-清除选择
    ClearCitySelect() {
      this.setData({
        isSelectCityLabel: "",
        isSelectDistrictLabel: "",
        isSelectprovinceLabel: "",
        isSelectCity: "",
        isSelectDistrict: "",
        isSelectprovince: "",
        cityCurrentIndex: 0,
        "searchForm.projectAreaCode": '',
        "searchForm.projectCityCode": '',
        "searchForm.projectProvinceCode": '',
        "searchForm.operatingIncomeValue": '',
        "searchForm.profitMin": '',
        "searchForm.profitMax": '',
        ['searchForm.current']: 1,
        showCity: false,
      });
      const child = this.selectComponent('#dropdownCity');
      child.toggle(false)
      this.getHomeData({
        key: "up"
      })
    },
    // 筛选-点击地区
    screenDistrict(e) {
      var {
        item,
        index,
        key
      } = getApp().utils.getParameter(e);
      this.setData({
        [key]: item.areaCode,
        "isSelectprovince": item.provinceCode,
        isSelectDistrictLabel: item.areaName
      });
    },
    // 筛选-点击城市
    screenCity(e) {
      var {
        item,
        index,
        key
      } = getApp().utils.getParameter(e);
      // 清除现有选择
      this.setData({
        isSelectCityLabel: "",
        isSelectDistrictLabel: "",
        isSelectprovinceLabel: "",
        isSelectCity: "",
        isSelectDistrict: "",
        isSelectprovince: "",
        cityCurrentIndex: 0,
        "searchForm.projectAreaCode": '',
        "searchForm.projectCityCode": '',
        "searchForm.projectProvinceCode": '',
        "searchForm.operatingIncomeValue": '',
        "searchForm.profitMin": '',
        "searchForm.profitMax": '',
        ['searchForm.current']: 1,
      });
      setTimeout(() => {
        this.setData({
          [key]: item.cityCode,
          cityCurrentIndex: 0,
          isSelectProvince: "",
        });
        this.citySearch({
          cityCode: item.cityCode,
          cityName: "",
        }, 'myDistrict')
      }, 200)
    },
    // 筛选-行业 
    screenProfessionItem(e) {
      let {
        index,
        pid
      } = e.currentTarget.dataset;
      var listData = this.data.searchForm[pid];
      if (listData.length != 0) {
        console.log(listData.includes(index))
        // 如果存在则去除，不存在则添加
        if (listData.includes(index)) {
          listData = listData.filter(item => item != index);
        } else {
          listData.push(index);
        }
        this.setData({
          ["searchForm." + pid]: listData
        })
      } else {
        this.setData({
          ["searchForm." + pid]: [index],
        })
      }

    },
    screenProfessionConfig() {
      this.getHomeData({
        key: 'down'
      });
      const child = this.selectComponent('#projectTypes');
      child.toggle(false)
    },
    screenProfessionClear() {
      this.setData({
        ['searchForm.projectIndustrys']: [],
        ['searchForm.projectTypes']: [],
        ['searchForm.current']: 1,
      })
      const child = this.selectComponent('#projectTypes');
      child.toggle(false);
      this.getHomeData({
        key: 'down'
      });
    },
    // 筛选-综合
    screenSynthesis(e) {
      this.setData({
        'searchForm.sortType': e.detail
      });
      this.getHomeData({
        key: 'down'
      })
    },
    getHomeData({
      key
    }) {
      var that = this;
      var child = this.selectComponent('#refresher');
      getApp().http.getHomeData(this.data.searchForm).then(res => {
        if (res.errorCode === 200) {
          var newData = res.data;
          if (that.data.searchForm.current !== 1) {
            let temp_list = that.data.list;
            newData = temp_list.concat(newData);
          }
          that.setData({
            list: newData
          });
          child?.allHideView();
          setTimeout(() => {
            if (res.data.length < that.data.searchForm.size) {
              console.log("后面没有更多了。");
              child?.setData({
                dataEnd: true
              });
            }
          }, 300);
        }
      }).catch(() => {
        console.log("请求首页数据失败")
      })
    },
    // 下拉事件
    pullDown() {
      const child = this.selectComponent('#refresher');
      child?.setData({
        dataEnd: false,
        loadingView: true,
      })
      this.setData({
        'searchForm.current': 1,
        'searchForm.size': 20,
      })
      this.getHomeData({
        key: 'down',
      })
    },
    // 上拉事件 
    pullUp() {
      let current = this.data.searchForm.current;
      current += 1;
      const child = this.selectComponent('#refresher');
      if (child?.dataEnd) return;
      child?.setData({
        loadingView: true,
        refresherTriggered: false,
      })
      this.setData({
        'searchForm.current': current,
      })
      setTimeout(() => {
        this.getHomeData({
          key: "up"
        })
      }, 400)
    },
    goDetails(e) {
      let id = e.currentTarget.id;
      console.log({
        id
      });
      if (id === undefined) {
        return;
      }
      getApp().nav.navTo({
        url: '/pages/details/details',
        data: {
          id
        },
      })
    },
    //开始定位
    startPosition(e) {
      wx.getFuzzyLocation({
        type: "gcj02",
        success(res) {
          console.log("请求信息::::", res);
        },
        fail(err) {
          console.log('失败信息', err);
        }
      })
    },
    openCity() {
      var that = this;
      // 查询是否授权
      // wx.authorize({
      //   scope: 'scope.userFuzzyLocation',
      //   success(res) {
      //     console.log("授权返回信息：：：：", res);
      //     if (res.errMsg === "authorize:ok") {
      //       // 开始请求定位信息
      //       // that.startPosition();
      //     }
      //   }
      // })
      this.setData({
        showCity: true,
      })
    },
    onScreenClickLeft(e) {
      this.setData({
        screenLeftSelect: e.currentTarget.dataset.id
      })
    },
    onScreenClickRight(e) {
      let {
        index,
        pid
      } = e.currentTarget.dataset
      this.setData({
        ['searchForm.' + pid]: index
      })
    },
    openScreen() {
      this.setData({
        showScreen: true,
      })
    },
    addss(e) {
      console.log("点击", e);
      // const child = this.selectComponent('#dropdownCity');
      // child.toggle(false)
      // this.setData({
      //   showScreen: false, 
      // }) 
    },
    onScreenClear() {
      this.setData({
        ['searchForm.establishmentTimeType']: null,
        ['searchForm.employeesNumberType']: null,
        ['searchForm.operatingIncomeType']: null,
        ['searchForm.operatingIncomeValue']: null,
        ['searchForm.profitType']: null,
        ['searchForm.profitMin']: null,
        ['searchForm.profitMax']: null,
        activateClass: false,
      });
      this.onScreenClose();
      this.getHomeData({
        key: "down"
      });
    },
    onScreenClose() {
      const child = this.selectComponent('#dropdownScreen');
      child.toggle(false)
      this.setData({
        showScreen: false,
      })
    },
    onCityClose() {
      const child = this.selectComponent('#dropdownCity');
      child.toggle(false)
      this.setData({
        showCity: false,
      })
    }, // 前往搜索
    goSearch() {
      getApp().nav.navTo({
        url: "/pages/search/search"
      })
    },
    stopTouchmove() {
      return this.data.isScroll;
    },
    isClose() {
      return false;
    }, // isOpen
    isOpen(e) {
      console.log(e);
    },
    setPaddingTop() {
      this.setData({
        top: getApp().globalData.view.menu.top + 5,
        navStatusBarHeight: getApp().globalData.view.navStatusBarHeight,
      })
    }
  }
})